package com.example.play.view

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.base.app.RouterPath
import com.example.common.entity.CommendEntity
import com.example.common.entity.SimpleVideoEntity
import com.example.common.event.CustomEvent
import com.example.common.mvi.BaseMviActivity
import com.example.image.GlideUtils
import com.example.play.R
import com.example.play.adapter.MovieVideoListAdapter
import com.example.play.adapter.SimpleVideoListAdapter
import com.example.play.adapter.VideoCommentListAdapter
import com.example.play.databinding.ActivityPlayBinding
import com.example.play.entity.AuthorEntity
import com.example.play.entity.MovieVideoEntity
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import org.greenrobot.eventbus.EventBus
import kotlin.math.log

//import android.graphics.Color
//import android.graphics.drawable.ColorDrawable
//import android.util.Log
//import android.view.Gravity.BOTTOM
//import android.view.LayoutInflater
//import android.view.View
//import android.view.ViewGroup
//import android.widget.EditText
//import android.widget.ExpandableListView
//import android.widget.ImageView
//import android.widget.PopupWindow
//import androidx.activity.viewModels
//import androidx.core.content.ContentProviderCompat.requireContext
//import androidx.fragment.app.Fragment
//import androidx.fragment.app.activityViewModels
//import androidx.lifecycle.lifecycleScope
//import androidx.recyclerview.widget.LinearLayoutManager
//import androidx.viewpager2.widget.ViewPager2
//import com.alibaba.android.arouter.facade.annotation.Autowired
//import com.alibaba.android.arouter.facade.annotation.Route
//import com.alibaba.android.arouter.launcher.ARouter
//import com.blankj.utilcode.util.GsonUtils
//import com.blankj.utilcode.util.ToastUtils
//import com.example.base.app.RouterPath
//import com.example.common.entity.CommendEntity
//import com.example.common.entity.SimpleVideoEntity
//import com.example.common.event.CustomEvent
//import com.example.common.mvi.BaseMviActivity
//import com.example.image.GlideUtils
//import com.example.image.glide.GlideImgLoader
//import com.example.play.R
//import com.example.play.adapter.MovieVideoListAdapter
//import com.example.play.adapter.PlayPageAdapter
//import com.example.play.adapter.SimpleVideoListAdapter
//import com.example.play.adapter.SimpleVideoListAdapter.ItemClickListener
//import com.example.play.adapter.VideoCommentListAdapter
//import com.example.play.databinding.ActivityPlayBinding
//import com.example.play.entity.AuthorEntity
//import com.example.play.entity.DanmuEntity
//import com.example.play.entity.MovieVideoEntity
//import com.example.play.entity.TabEntity
//import com.example.play.intent.PlayViewIntent
//import com.example.play.state.PlayUiState
//import com.example.play.vm.PlayViewModel
//import com.flyco.tablayout.listener.CustomTabEntity
//import com.flyco.tablayout.listener.OnTabSelectListener
//import dagger.hilt.android.AndroidEntryPoint
//import kotlinx.coroutines.launch
//import master.flame.danmaku.controller.DrawHandler
//import master.flame.danmaku.danmaku.model.BaseDanmaku
//import master.flame.danmaku.danmaku.model.DanmakuTimer
//import master.flame.danmaku.danmaku.model.IDanmakus
//import master.flame.danmaku.danmaku.model.android.DanmakuContext
//import master.flame.danmaku.danmaku.model.android.Danmakus
//import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
//import org.greenrobot.eventbus.EventBus
//import java.text.SimpleDateFormat

@AndroidEntryPoint
@Route(path = RouterPath.PATH_PLAY_PAGE)
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {
//    @Autowired
//    @JvmField
//    var videoPath:String = ""
//    @JvmField
//    @Autowired
//    var userId:String = ""
//    @Autowired
//    @JvmField
//    var channelId :String = ""
//    @Autowired
//    @JvmField
//    var typeId :Int = -1
//    @Autowired
//    @JvmField
//    var moduleType: Int = 0 //默认从首页进入
//    @Autowired
//    @JvmField
//    var itemId: String = ""
//    @Autowired
//    @JvmField var videoTypeId: Int = -1 //推荐
//
//
//    private lateinit var mDanmuContext : DanmakuContext
//
//    private var pageIndex = 1
//    private var pageSize = 10
//    private val simpleVideoList = mutableListOf<SimpleVideoEntity>()
//    private val movieVideoEntity= mutableListOf<MovieVideoEntity>()
//    private lateinit var simpleVideoListAdapter: SimpleVideoListAdapter
//    private lateinit var movieVideoListAdapter: MovieVideoListAdapter
//    var popupWindow: PopupWindow? = null
//    private val mViewModel: PlayViewModel by viewModels()
//    override fun getLayoutId(): Int = R.layout.activity_play
//
//    override fun initViews() {
//        //ARouter依赖注入来获取参数(方式一)
//        //ARouter.getInstance().inject(this)
//        //ARouter本质还是Intent携带参数（方式二）
//        intent.extras?.apply {
//            videoPath = getString("videoPath").toString()
//            userId = getString("userId").toString()
//            channelId = getString("channelId").toString()
//            itemId = getString("itemId").toString()
//            typeId = getInt("typeId")
//            moduleType = getInt("moduleType")
//        }
//
//        //使用GSY播放视频
//        mDataBinding.videoPlayer?.apply {
//            setUp(videoPath,false,"")
//            backButton.visibility = View.GONE
//            isLooping = true
//            //全屏显示
//            fullscreenButton.setOnClickListener {
//                startWindowFullscreen(this.context,false,true)
//            }
//        }
//
//        simpleVideoListAdapter = SimpleVideoListAdapter(simpleVideoList).apply {
//            setOnItemClickListener(object : SimpleVideoListAdapter.ItemClickListener {
//                override fun onItemChildClick(v: View, position: Int, entity: SimpleVideoEntity) {
//                    //使用EventBus给外部Activity发送事件（方案一）
//                    EventBus.getDefault().post(CustomEvent("PlayActivity", entity, 0))
//                    //使用LiveDataBus发送事件（方案二）
//                }
//            })
//        }
//
//        movieVideoListAdapter=MovieVideoListAdapter(movieVideoEntity).apply {
//            setOnItemClickListener(object : MovieVideoListAdapter.ItemClickListener {
//                override fun onItemChildClick(v: View, position: Int, entity: MovieVideoEntity) {
//                    //使用EventBus给外部Activity发送事件（方案一）
//                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,1))
//                    //使用LiveDataBus发送事件（方案二）
//                }
//
//            })
//        }
//
//
//        mDataBinding.rvPlay.apply {
//
//            layoutManager= LinearLayoutManager(this@PlayActivity, LinearLayoutManager.VERTICAL,false)
//            if (moduleType == 0){
//                adapter = simpleVideoListAdapter
//            }else{
//                adapter = movieVideoListAdapter
//            }
//        }
//
//
//
//        //点击弹幕按钮事件
//        mDataBinding.ivDanmuImg.setOnClickListener {
//            if(mDataBinding.llDanmuLayout.visibility == View.VISIBLE){
//                mDataBinding.llDanmuLayout.visibility = View.GONE
//            } else {
//                mDataBinding.llDanmuLayout.visibility = View.VISIBLE
//            }
//        }
//
//        //发送弹幕按钮事件
//        mDataBinding.ivDanmuSend.setOnClickListener {
//            //校验一下弹幕内容
//            var danmuContent = mDataBinding.etDanmuInput.text.toString().trim()
//            if (!danmuContent.isNullOrEmpty()){
//                sendVideoDanmu(danmuContent)
//            }
//        }
//
//        //初始化弹幕
//        initVideoDanmu()
//
//
//    }
//
//    override suspend fun sendViewIntent() {
//        mViewModel.channel.send(PlayViewIntent.LoadAuthorInfo(userId))
//
//            //加载视频列表
//            when(moduleType){
//                //从首页模块进入
//                0 -> {
//                    if (videoTypeId == -1){
//                        mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideo(pageIndex, pageSize))
//                    } else {
//                        mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoByChannelId(channelId, pageIndex, pageSize))
//                    }
//                }
//                //从放映厅模块进入
//                1 -> {
//                    if (videoTypeId == -1){
//                        mViewModel.channel.send(PlayViewIntent.LoadRecommendMultiVideo(pageIndex, pageSize))
//                    } else {
//                        mViewModel.channel.send(PlayViewIntent.LoadMultiVideoByTypeId(videoTypeId, pageIndex, pageSize))
//                    }
//                }
//            }
//
//
//    }
//
//    override suspend fun collectUIState() {
//        mViewModel.uiSharedFlow.collect {
//            when (it) {
//                is PlayUiState.LoadAuthorSuccess -> updateAuthorInfo(it.entity)
//                is PlayUiState.LoadVideoDanmuSuccess -> updateVideDanmu(it.list)
//                is PlayUiState.LoadSimpleVideoSuccess -> updateVideoList(it.list)
//                is PlayUiState.LoadMultiVideoSuccess-> updateRecommendMutilVideo(it.list)
//                else -> {}
//            }
//
//        }
//    }
//
//    private fun updateVideoList(list: List<SimpleVideoEntity>) {
//        if (pageIndex == 1) {
//            simpleVideoList.clear()
//        }
//        simpleVideoList.addAll(list)
//        simpleVideoListAdapter.notifyDataSetChanged()
//
//    }
//
//    private fun updateVideDanmu(list: List<DanmuEntity>){
//        Log.i("=============", "updateVideDanmu: "+ GsonUtils.toJson(list))
//
//    }
//
//    private fun updateAuthorInfo(entity: AuthorEntity){
//        Log.i("=============", "updateAuthorInfo: "+ GsonUtils.toJson(entity))
//        GlideImgLoader.loadCircleImage(this@PlayActivity, entity.avatar_url, mDataBinding.ivUserIcon)
//        mDataBinding.apply {
//            tvUserName.text = entity.name
//            tvUserDesc.text = entity.author_desc
//            tvLikeCount.text = entity.followerscount.toString()
//            tvSendTime.text = entity.ctime
//        }
//    }
//
//    private fun updateRecommendMutilVideo(list: List<MovieVideoEntity>) {
//        if (pageIndex ==1){
//            movieVideoEntity.clear()
//        }
//        movieVideoEntity.addAll(list)
//        movieVideoListAdapter.notifyDataSetChanged()
//    }
//
//
//
//    override fun handEvent(event: CustomEvent) {
//        when (event.type) {
//            0 -> {
//                val simpleVideo = event.data as SimpleVideoEntity
//                mDataBinding.videoPlayer.apply {
//                    setUp(simpleVideo.videopath, true, "")
//                    startPlayLogic()
//                }
//            }
//
//            1 -> {
//                val movieVideo = event.data as MovieVideoEntity
//                mDataBinding.videoPlayer.apply {
//                    setUp(movieVideo.videopath, true, "")
//                    startPlayLogic()
//                }
//            }
//        }
//    }
//
//
//
//
//    /**
//     * 初始化弹幕
//     */
//    private fun initVideoDanmu(){
//        //创建弹幕上下文
//        mDanmuContext = DanmakuContext.create()
//        //准备弹幕
//        mDataBinding.danmuView.apply {
//            prepare(object :BaseDanmakuParser(){
//                override fun parse(): IDanmakus {
//                 return Danmakus()
//                }
//            },mDanmuContext)
//
//            //设置回调
//            setCallback(object :DrawHandler.Callback{
//                override fun prepared() {
//
//                }
//
//                override fun updateTimer(timer: DanmakuTimer?) {
//
//                }
//
//                override fun danmakuShown(danmaku: BaseDanmaku?) {
//
//                }
//
//                override fun drawingFinished() {
//
//                }
//
//            })
//        }
//    }
//
//    /**
//     * 发送弹幕
//     */
//    private fun  sendVideoDanmu(content:String){
//        //封装弹幕实体
//        var danmuEntity = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
//            text = content
//            textSize = 30f
//            textColor = Color.YELLOW
//            padding = 10
//            time = 500//延时时间
//            borderColor = Color.RED
//        }
//
//        //将弹幕实体添加到弹幕组件中
//        mDataBinding.danmuView.apply {
//            addDanmaku(danmuEntity)
//            start()
//        }
//
//        //清理发送弹幕输入框
//        mDataBinding.etDanmuInput.setText("")
//        mDataBinding.llDanmuLayout.visibility = View.GONE
//    }
//
//    override fun onResume() {
//        super.onResume()
//        mDataBinding?.videoPlayer?.startPlayLogic()
//    }
//
//    override fun onPause() {
//        super.onPause()
//        mDataBinding?.videoPlayer?.onVideoPause()
//    }
//
//    override fun onDestroy() {
//        mDataBinding?.videoPlayer?.release()
//        super.onDestroy()
//    }































































    @Autowired
    @JvmField var videoPath:String=""
    @Autowired
    @JvmField var userId:String=""
    @Autowired
    @JvmField var channelId:String=""
    @Autowired
    @JvmField var typeId:Int=-1
    @Autowired
    @JvmField var itemId:String=""
    @Autowired
    @JvmField var moduleType:Int=0//默认从首页进入

    var videoTypeId:Int=-1//默认从首页进入

    private lateinit var mDanmuContext: DanmakuContext

    private var pageIndex=1
    private var pageSize=10
    private val simpleVideoEntity= mutableListOf<SimpleVideoEntity>()
    private val movieVideoEntity= mutableListOf<MovieVideoEntity>()
    private lateinit var simpleVideoListAdapter: SimpleVideoListAdapter
    private lateinit  var movieVideoListAdapter:MovieVideoListAdapter



    private val mViewModel: PlayViewModel by viewModels ()
    var popupWindow: PopupWindow? = null
    private val commentList = mutableListOf<CommendEntity>()
    private lateinit var commentAdapter: VideoCommentListAdapter

    override fun getLayoutId(): Int = R.layout.activity_play

    override fun initViews() {
        //方式1
        // ARouter.getInstance().inject(this)
        //方式2
        intent.extras?.apply {
            videoPath = getString("videoPath").toString()
            userId = getString("userId").toString()
            channelId = getString("channelId").toString()
            itemId = getString("itemId").toString()
            typeId = getInt("typeId")
            moduleType=getInt("moduleType")
        }
        ToastUtils.showLong("${videoPath}        ,${userId}      ,${channelId}     ,${itemId}     ,${typeId}      ,${moduleType}")
        commentAdapter= VideoCommentListAdapter(commentList)
        //播放GSY播放视频
        mDataBinding.videoPlayer?.apply {
            setUp(videoPath, false, "")
            backButton.visibility= View.GONE
            isLooping=true
            //全屏显示
            fullscreenButton.setOnClickListener {
                startWindowFullscreen(this.context,false,true)
            }
        }

//        //点击评论
//        mDataBinding.llComment.setOnClickListener {
//            showPopupWindow(it)
//        }

        //点击事件
//        mDataBinding.tvDanmu.setOnClickListener {
//            mDataBinding.llDanmuLayout.visibility=View.VISIBLE
//        }

        //发送弹幕按钮点击事件
//        mDataBinding.ivDanmuSend.setOnClickListener {
//            //校验弹幕内容
//            var danmuContent=mDataBinding.etDanmuInput.editableText.toString().trim()
//            if(!danmuContent.isNullOrEmpty()){
//                sendVideoDanmu(danmuContent)
//            }
//        }
        //初始化弹幕
        initVideoDanmu()

        simpleVideoListAdapter=SimpleVideoListAdapter(simpleVideoEntity).apply {
            setOnItemClickListener(object : SimpleVideoListAdapter.ItemClickListener {
                override fun onItemChildClick(v: View, position: Int, entity: SimpleVideoEntity) {
                    //使用EventBus给外部Activity发送事件（方案一）
                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,0))
                    //使用LiveDataBus发送事件（方案二）
                }
            })
        }
        movieVideoListAdapter=MovieVideoListAdapter(movieVideoEntity).apply {
            setOnItemClickListener(object : MovieVideoListAdapter.ItemClickListener {
                override fun onItemChildClick(v: View, position: Int, entity: MovieVideoEntity) {
                    //使用EventBus给外部Activity发送事件（方案一）
                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,1))
                    //使用LiveDataBus发送事件（方案二）
                }

            })
        }
        mDataBinding.rvPlay.apply {
            layoutManager= LinearLayoutManager(this@PlayActivity, LinearLayoutManager.VERTICAL,false)
            if (moduleType == 0){
                adapter = simpleVideoListAdapter
            }
            if (moduleType == 1){
                adapter = movieVideoListAdapter
            }
        }
    }
    //评论弹窗
//    private fun showPopupWindow(it: View?) {
//        val inflater = LayoutInflater.from(this)
//        val popupView = inflater.inflate(R.layout.comment_list_layout, null)
//        val width = ViewGroup.LayoutParams.MATCH_PARENT
//        val height = ViewGroup.LayoutParams.WRAP_CONTENT
//        popupWindow = PopupWindow(popupView, width, height).apply {
//            // 设置背景，这是点击外部关闭弹窗的必要条件
//            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
//            // 设置是否可点击
//            isFocusable = true
//            // 设置点击外部是否关闭
//            isOutsideTouchable = true
//            // 设置动画效果
//            animationStyle = R.style.BottomSheetDialog
//        }
//        popupView.findViewById<ExpandableListView>(R.id.expand_list).setAdapter(commentAdapter)
//        popupView.findViewById<ImageView>(R.id.iv_commend_send).setOnClickListener {
//            var et_commend_input=popupView.findViewById<EditText>(R.id.et_commend_input)
//            if (et_commend_input.text.toString().trim().isEmpty()){
//                ToastUtils.showLong("请输入评论内容")
//                return@setOnClickListener
//            }else{
//                var comment= CommendEntity(
//                    agreenum = 270,
//                    content = et_commend_input.text.toString().trim(),
//                    createtime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()),
//                    datatype = 0,
//                    id = 0,
//                    itemid = itemId.toLong(),
//                    nickname = "视频号007",
//                    replyList = mutableListOf(),
//                    replytotal = 10,
//                    userid = 0,
//                    userlogo = "https://img1.baidu.com/it/u=2306417155,1148748420&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
//                )
//                lifecycleScope.launch {
//                    mViewModel.channel.send(PlayViewIntent.PublishComment(comment))
//                }
//                et_commend_input.text.clear()
//            }
//        }
//        popupWindow?.showAtLocation(it, BOTTOM, 0, 0)
//    }

    override fun handEvent(event: CustomEvent) {
        when(event.type){
            0-> {
                val simpleVideo = event.data as SimpleVideoEntity
                mDataBinding.videoPlayer.apply {
                    setUp(simpleVideo.videopath,true,"")
                    startPlayLogic()
                }
            }
            1-> {
                val movieVideo = event.data as MovieVideoEntity
                mDataBinding.videoPlayer.apply {
                    setUp(movieVideo.videopath,true,"")
                    startPlayLogic()
                }
            }
        }
    }
    private fun initVideoDanmu() {
        //创建
        mDanmuContext= DanmakuContext.create()
        //准备弹幕
//        mDataBinding.danmuView.apply {
//            //准备
//            prepare(object :BaseDanmakuParser(){
//                override fun parse(): IDanmakus {
//                    return Danmakus()
//                }
//
//            },mDanmuContext)
//            //设置回调
//            setCallback(object :DrawHandler.Callback{
//                override fun prepared() {
//
//                }
//
//                override fun updateTimer(timer: DanmakuTimer?) {
//
//                }
//
//                override fun danmakuShown(danmaku: BaseDanmaku?) {
//
//                }
//
//                override fun drawingFinished() {
//
//                }
//            })
//        }
    }

    /**
     * 发送弹幕
     */
//    private fun sendVideoDanmu(danmuContent: String) {
//        mDataBinding.danmuView.clear()
//        //封装弹幕实体
//        var danmuEntity =mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
//            text=danmuContent
//            textSize=30f
//            textColor= Color.YELLOW
//            padding=10
//            time=500
//            borderColor=Color.RED
//        }
//        mDataBinding.danmuView.apply {
//            addDanmaku(danmuEntity)
//            start()
//        }
//        //清理一下输入框
//        mDataBinding.etDanmuInput.setText("")
//        mDataBinding.llDanmuLayout.visibility=View.GONE
//    }

    override fun onResume() {
        super.onResume()
        mDataBinding?.videoPlayer?.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mDataBinding?.videoPlayer?.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataBinding?.videoPlayer?.release()
        popupWindow?.dismiss()
    }
    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        //获取作者信息
        mViewModel.channel.send(PlayViewIntent.LoadAuthorInfo(userId))
        //加载视频列表
        when (moduleType){
            0->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoByChannelId(channelId,pageIndex,pageSize))
                }
//                mViewModel.channel.send(PlayViewIntent.LoadVideoCommends(0,itemId))
            }
            1->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendMultiVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadMultiVideoByTypeId(typeId,pageIndex,pageSize))
                }
//                mViewModel.channel.send(PlayViewIntent.LoadVideoCommends(1,itemId))
            }
        }
    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiSharedFlow.collectLatest {
            when(it){
                is PlayUiState.LoadAuthorSuccess-> updateAuthorById(it.list)
                is PlayUiState.LoadSimpleVideoSuccess-> updateRecommendSimpleVideo(it.list)
                is PlayUiState.LoadMultiVideoSuccess-> updateRecommendMutilVideo(it.list)
//                is PlayUiState.LoadVideoCommendsSuccess -> showVideoCommendList(it.list)
                else->{}
            }
        }
    }

    private fun showVideoCommendList(list: List<CommendEntity>) {
        commentList.clear()
        commentList.addAll(list)
        commentAdapter.notifyDataSetChanged()
    }

    private fun updateAuthorById(list: AuthorEntity) {
        GlideUtils.loadCircleImage(this,list.avatar_url,mDataBinding.ivUserIcon)
        mDataBinding.apply {
            tvUserName.text=list.name
            tvUserDesc.text=list.author_desc
            tvLikeCount.text=list.followerscount
            tvSendTime.text=list.ctime
        }
    }
    private fun updateRecommendSimpleVideo(list: List<SimpleVideoEntity>) {
        if (pageIndex ==1){
            simpleVideoEntity.clear()
        }
        simpleVideoEntity.addAll(list)
        simpleVideoListAdapter.notifyDataSetChanged()
    }

    private fun updateRecommendMutilVideo(list: List<MovieVideoEntity>) {
        if (pageIndex ==1){
            movieVideoEntity.clear()
        }

        movieVideoEntity.addAll(list)
        movieVideoListAdapter.notifyDataSetChanged()
    }




}